package org.s3.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.s3.project.entity.AddressBook;
import org.s3.project.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author cfx
 * @version 1.0
 * @Description
 * @date 2025/2/9 9:14
 */
@CrossOrigin(origins = "*")
@RestController
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;
    @GetMapping("SelectAddressBook")
    public List<AddressBook> SelectAddressBook(@RequestParam("userid") int userid){
        return addressBookService.getDefaultAddressBook(userid);
    }
    @PostMapping("AddAddressBook")
    public int AddAddressBook(@RequestBody AddressBook addressBook){
        return addressBookService.addAddressBook(addressBook);
    }
    @PostMapping("deleteAddressBook/{id}")
    public int deleteAddressBook(@PathVariable("id") int id){
        return addressBookService.deleteAddressBook(id);
    }
//    删除地址
    @GetMapping("deleteadders")
    public Boolean deleteAdders(@RequestParam String id){

        return  addressBookService.removeById(id);
    }
    //修改地址
    @PostMapping("updateAddressBook")
    public String updateAddressBook(@RequestBody AddressBook addressBook){
        Boolean isa=addressBookService.updateById(addressBook);
        //如果成功  判断客户是否勾选默认地址
        if(isa){
            //判断他的默认地址为一
            if(addressBook.getIs_Default()==1){
                // 如果为一  调用修改方法把其他地址全部改成0
                addressBookService.UpdateIsDefault(addressBook.getUser_id(),addressBook.getId());
            }
        }
        return  isa? "成功" : "不成功";
    }
//    查询修改的地址
    @GetMapping("selectadderss")
    public AddressBook selectadderss(@RequestParam String id) {
        QueryWrapper<AddressBook> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        java.util.List<AddressBook> addressBookList = addressBookService.list(queryWrapper);
        if (!addressBookList.isEmpty()) {
            return addressBookList.get(0);
        }
        return null;
    }
    //新增地址
    @PostMapping("InsertAddressBook")
    public String InsertAddressBook(@RequestBody AddressBook addressBook){
        Boolean isa=addressBookService.save(addressBook);
        //如果成功  判断客户是否勾选默认地址
        if(isa){
            //判断他的默认地址为一
            if(addressBook.getIs_Default()==1){

                // 如果为一  调用修改方法把其他地址全部改成0
                addressBookService.UpdateIsDefault(addressBook.getUser_id(),addressBook.getId());
            }
        }
        return  isa? "成功" : "不成功";
    }
}
